package top.shiyiri.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Aunean
 * @date 2022/2/10 15:48
 */
public class AdminFilter implements Filter {

    public AdminFilter() {
        System.out.println("AdminFilter()构造方法");
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter的init(FilterConfig filterConfig)初始化");

        //1.获取Filter的名称 filter-name的内容
        System.out.println("filter-name的值是：" + filterConfig.getFilterName());
        //2.获取Filter中配置init-param初始化参数
        System.out.println("init-param初始化参数username的值是：" + filterConfig.getInitParameter("username"));
        //3.获取ServletContext对象
        System.out.println(filterConfig.getServletContext());
    }

    /**
     * doFilter方法，专门用于拦截请求，用于权限检查
     * @param servletRequest
     * @param servletResponse
     * @param filterChain 过滤器链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter的doFilter()");
        System.out.println("doFilter进行拦截");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        HttpSession session = httpServletRequest.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
        } else {
            //让程序继续往下访问用户的目标资源
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("Filter的destroy()");
    }
}
